package com.huawei.app.demo.util;

import android.app.Service;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * AudioFragment的工具类
 * @since 2021-2-28
 */

public class SoundUtils {
    private static final String TAG = SoundUtils.class.getSimpleName();
    private MediaRecorder mRecorder = null;
    private MediaPlayer mPlayer = null;
    private File audioFile;


    /**
     * 开始录音
     */
    public void startRecording() {
        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
        try {
            audioFile = File.createTempFile("record_", ".amr");
            mRecorder.setOutputFile(audioFile.getAbsolutePath());
            mRecorder.prepare();

        } catch (IOException e) {
            Log.e(TAG, "prepare() failed" + e.getMessage());
        }
        mRecorder.start();
        Log.d(TAG, "startRecording: startRecording");

    }

    /**
     * 停止录音
     */
    public void stopRecording() {
        if (mRecorder != null) {
            mRecorder.stop();
            mRecorder.release();
            mRecorder = null;
        }
        Log.d(TAG, "stopRecording: stopRecording");
    }

    public boolean isAudioFileexist(){
        try {
            if (audioFile.exists()) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e){
            return false;
        }
    }


    public String getAudioFile(){return this.audioFile.getAbsolutePath();}

    /**
     * 根据filename去播放音频
     * @param fileName
     */
    public void startPlay(String fileName){
            mPlayer = new MediaPlayer();
            try {
                mPlayer.setDataSource(fileName);
                mPlayer.prepare();
                mPlayer.start();
                Log.d(TAG, "startPlay: playing");
            } catch (IOException e) {
                Log.e(TAG, "prepare() failed" + e.getMessage());
            }
    }

    /**
     * 停止播放
     */
    public void stopPlaying() {
        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
    }
}
